import {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Form, message, Upload } from 'antd';
import { getToken } from '../../utils/const.ts';
import { UploadOutlined } from '@ant-design/icons';
import { useEffect } from 'react';
import { request } from '../../utils/request.ts';

const Edit = ({ open, setOpen, actionRef, record, }) => {
  const [form] = Form.useForm();
  const uploadProps = {
    headers: {
      token: getToken(),
    },
    maxCount: 1,
  }

  useEffect(() => {
    if (open) {
      const initial = {
        ...record,
        bgPic: record?.bgPic
          ? [{
              uid: '-1',
              name: '证书背景图.png',
              status: 'done',
              url: record.bgPic,
            }]
          : [],
      };
      form.setFieldsValue(initial);
    }
  }, [open, record, form]);

  return (
    <>
      <ModalForm
        title={record?.id ? "编辑证书" : "新增证书"}
        form={form}
        autoFocusFirstInput
        open={open}  
        width={500}
        layout="horizontal" // 关键点
        labelCol={{ span: 6 }} // label 占 6/24
        wrapperCol={{ span: 18 }} // 输入框占 18/24
        modalProps = {{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        onFinish={async (values) => {
          const { bgPic, ...other } = values;
          try {
            const res = await request(record?.id ? '/api/card/update' : '/api/card/save', {
              method: 'POST',
              data: {
                ...other,
                bgPic: bgPic && bgPic[0]?.response?.data ? bgPic[0].response.data : record?.bgPic,
                id: record?.id,
              },
            });
            if (res.data) {
              message.success('提交成功');
              setOpen(false);
              actionRef.current?.reload();
            } else {
              message.error(res.msg);
            }
          } catch (error) {
            console.error('Failed to submit data:', error);
          }
          return true;
        }}
        >
          <ProFormText 
            name="name" 
            label="证书名称"
            rules={[{ required: true, }]}
          />
          <ProFormSelect
            options={[
              {
                value: '1',
                label: '教练',
              },
              {
                value: '2',
                label: '学员',
              },
            ]}
            name="type"
            label="证书类型"
            rules={[{ required: true, message: '请选择证书类型' }]}
          />
          <ProFormText
            name="price"
            label="证书认证费用"
            rules={[{ required: true, }]}
          />
        <ProFormText
          name="remark"
          label="证书描述"
          rules={[{ required: true, }]}
        />
        <Form.Item
          label="证书背景图"
          name="bgPic"
          valuePropName="fileList"
          getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList}
          rules={[
            { required: true, message: '请上传证书背景图片' },
          ]}
        >
          <Upload name="file" action="/api/uploadFile" {...uploadProps} listType="picture">
            <Button icon={<UploadOutlined />}>上传证书背景图片</Button>
          </Upload>
        </Form.Item>
      </ModalForm >
    </>
  );
};
export default Edit;